class Solution {
public:
    int ans = 0;
    int longestUnivaluePath(TreeNode* root) {
        dfs(root, -1);
        return ans;
    }

    int dfs(TreeNode* root, int val) {
        if (root == nullptr) return 0;
        int left = dfs(root->left, root->val), right = dfs(root->right, root->val);
        ans = max(ans, left + right);
        return root->val == val ? max(left, right) + 1 : 0;
    }
};
